package cn.net.wanji.config;

import cn.net.wanji.utils.StringUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guodejun
 * @createTime 2022/11/1 14:15
 * @description
 */
@Configuration
@Data
public class ApplicationConfig {

    @Value("${file.savePath}")
    private String fileSavePath;

    private String[] fileSavePaths = null;

    @Value("${file.nginx}")
    private String fileNginx;

    private String[] fileNginxs = null;

    @Value("${file.disc-shell}")
    private String discShell;


    @Value("${kafka.servers}")
    private String kafkaServers;


    /**
     * pre-data-topic: pre_data
     * data-topic: data
     * ai-topic: ai_topic
     */
    @Value("${kafka.pre-data-topic}")
    private String preDataTopic;

    @Value("${kafka.data-topic}")
    private String dataTopic;

    @Value("${kafka.ai-topic}")
    private String aiTopic;

    @Value("${pre.data.timeout}")
    private String preDataTimeout;

    /**
     * websocket:
     * ai-address: ws://localhost:8083
     * twin-address: ws://localhost:8084
     *
     * @return
     */

    @Value("${websocket.ai-address}")
    private String aiAddress;

    @Value("${websocket.twin-address}")
    private String twinAddress;

    @Value("${file.memory}")
    private String fileMemory;

    @Value("${event.overSpeed}")
    private String overSpeed;

    @Value("${event.lowSpeed}")
    private String lowSpeed;

    public String getKafkaServers() {
        return kafkaServers;
    }

    public String getPreDataTopic() {
        return preDataTopic;
    }

    public String getDataTopic() {
        return dataTopic;
    }

    public String getAiTopic() {
        return aiTopic;
    }


    public String getAiAddress() {
        return aiAddress;
    }

    public String getTwinAddress() {
        return twinAddress;
    }

    public String getFileSavePath(String recordId) {

        // 首次调用 初始化 fileSavePaths
        if (fileSavePaths == null) {
            fileSavePaths = fileSavePath.split(";");
        }
        int index = getIndexByHashCode(recordId, fileSavePaths.length);
        return fileSavePaths[index];
    }

    public String getFileNginx(String recordId) {
        if (fileNginxs == null) {
            fileNginxs = fileNginx.split(";");
        }
        int index = getIndexByHashCode(recordId, fileNginxs.length);
        return fileNginxs[index];
    }


    private final List<String> shell = new ArrayList<>();

    public List<String> getShell() {
        if (shell.size() == 0 && !StringUtils.isEmpty(discShell)) {
            shell.add(discShell);
        }
        return shell;
    }


    private static int getIndexByHashCode(String recordId, int arrayLen) {
        int hashCode = Math.abs(recordId.hashCode());
        return hashCode % arrayLen;
    }


}
